import { FormConfig } from '../types'
import { formLogger } from './logger'

/**
 * 表单配置验证器
 * 确保配置数据的完整性和安全性
 */

export interface ValidationResult {
  isValid: boolean
  errors: string[]
  warnings: string[]
  sanitizedConfig: FormConfig
}

export function validateFormConfig(config: FormConfig): ValidationResult {
  const errors: string[] = []
  const warnings: string[] = []
  const sanitizedConfig: FormConfig = JSON.parse(JSON.stringify(config))

  try {
    // 基础字段验证
    if (!config.title || typeof config.title !== 'string') {
      errors.push('表单标题必须是非空字符串')
      sanitizedConfig.title = '未命名表单'
    }

    if (!config.viewType || typeof config.viewType !== 'string') {
      errors.push('viewType必须是非空字符串')
      sanitizedConfig.viewType = 'defaultForm'
    }

    if (!Array.isArray(config.fields)) {
      errors.push('fields必须是数组')
      sanitizedConfig.fields = []
    }

    // 字段验证
    sanitizedConfig.fields = config.fields.map((field, index) => {
      const sanitizedField = { ...field }

      if (!field.id || typeof field.id !== 'string') {
        errors.push(`字段${index}缺少有效的id`)
        sanitizedField.id = `field_${index}`
      }

      if (!field.type || typeof field.type !== 'string') {
        errors.push(`字段${field.id}缺少有效的类型`)
        sanitizedField.type = 'input'
      }

      // 验证类型是否在允许的范围内
      const allowedTypes = ['textarea', 'input', 'tags']
      if (!allowedTypes.includes(field.type)) {
        warnings.push(`字段${field.id}的类型"${field.type}"不在允许范围内，将设置为input`)
        sanitizedField.type = 'input'
      }

      if (!field.label || typeof field.label !== 'string') {
        warnings.push(`字段${field.id}缺少标签`)
        sanitizedField.label = sanitizedField.id
      }

      // 验证字段值
      if (field.value !== undefined && field.value !== null) {
        if (field.type === 'tags' && !Array.isArray(field.value)) {
          warnings.push(`字段${field.id}的值应该是数组`)
          sanitizedField.value = []
        }
      }

      return sanitizedField
    })

    // 上下文验证
    if (config.context) {
      if (config.context.codeSnippet && typeof config.context.codeSnippet === 'string') {
        if (config.context.codeSnippet.length > 50000) {
          warnings.push('代码片段过长，可能影响性能')
        }
      }
    }

    // 记录验证结果
    if (errors.length > 0) {
      formLogger.error('表单配置验证失败', { errors, config })
    }
    if (warnings.length > 0) {
      formLogger.warn('表单配置验证警告', { warnings, config })
    }
  } catch (error) {
    errors.push('配置验证过程中发生异常: ' + error)
    formLogger.error('配置验证异常', error)
  }

  return {
    isValid: errors.length === 0,
    errors,
    warnings,
    sanitizedConfig
  }
}
